let canvas1 = document.getElementById('canvas1');
let audio1 = document.getElementById('audio1');

let windowWidth = window.innerWidth;
let windowHeight = window.innerHeight;

canvas1.width = windowWidth;
canvas1.height = windowHeight;

plot.width = windowWidth;
plot.height = 50;

// 下部控制条
initControls(audio1);

initDrawContext(canvas1);

let animationHandler = null;

let audioCtx = null;
let source = null;
let analyser = null;

audio1.addEventListener('play', function(){
	if(!audioCtx){
		audioCtx = new (window.AudioContext || window.webkitAudioContext)();
		source = audioCtx.createMediaElementSource(audio1);

		analyser = audioCtx.createAnalyser();

		source.connect(analyser);
		source.connect(audioCtx.destination);

	}

	let sourceArr = new Uint8Array(analyser.frequencyBinCount);

	function framework(){
		analyser.getByteTimeDomainData(sourceArr)
		console.log(sourceArr);
		draw(sourceArr, windowWidth, windowHeight);
		animationHandler = requestAnimationFrame(framework);
	}

	framework();

	console.log('start play');
})

audio1.addEventListener('pause', function(){
	console.log('pause play');
	cancelAnimationFrame(animationHandler);
})

let canvas1Rect = canvas1.getBoundingClientRect();

let startX = 0;
let startY = 0;
let drawing = false;

let rectList = [{
	x: windowWidth / 2 - 50,
	y: windowHeight / 2 - 50,
	w: 100,
	h: 100
}];
canvas1.addEventListener('mousedown', function(evt){
	if(evt.button === 2) return;
	startX = evt.clientX - canvas1Rect.x;
	startY = evt.clientY - canvas1Rect.y;
	drawing = true;
})

canvas1.addEventListener('mouseup', function(evt){
	let x = evt.clientX - canvas1Rect.x;
	let y = evt.clientY - canvas1Rect.y;

	rectList.push({
		x: startX > x ? x : startX,
		y: startY > y ? y : startY,
		w: Math.abs(x - startX),
		h: Math.abs(y - startY)
	})

	startX = 0;
	startY = 0;
	drawing = false;
})

canvas1.addEventListener('mousemove', function(evt){
	if(!drawing) return;
	let tempx = evt.clientX - canvas1Rect.x;
	let tempy = evt.clientY - canvas1Rect.y;

	let x = startX > tempx ? tempx : startX;
	let y = startY > tempy ? tempy : startY;
	let w = Math.abs(tempx - startX);
	let h = Math.abs(tempy - startY);

	canvasCtx.clearRect(0, 0, windowWidth, windowHeight);
	drawRectList(canvasCtx);
	// canvasCtx.fillStyle = 'rgb(0, 0, 0)';
	// for(let i = 0; i < rectList.length; i++){
	// 	let rect = rectList[i];
	// 	canvasCtx.fillRect(rect.x, rect.y, rect.w, rect.h);
	// }
	// console.log(x, y, w, h);
	canvasCtx.fillRect(x, y, w, h);
})


function drawRectList(ctx, offset = 0){
	let halfOffset = offset / 2;
	canvasCtx.fillStyle = 'rgb(0, 0, 0)';
	for(let i = 0; i < rectList.length; i++){
		let rect = rectList[i];
		ctx.fillRect(rect.x - halfOffset, rect.y - halfOffset, rect.w + offset, rect.h + offset);
	}
}

drawRectList(canvasCtx);

